class RoleListSelect extends React.Component{

    constructor(props){
        super(props);
        this.state = {roles : ['']};
        this.level = 0;
    }

    get value(){
        return this.refs.roleSelect.value;
    }

    set value(value){
        this.refs.roleSelect.value = value;
    }

    get roleCode(){
        let selectedIndex = this.refs.roleSelect.selectedIndex;
        return this.refs.roleSelect[selectedIndex].dataset.rolecode;
    }

    init(roles){
        this.state.roles = [];
        if(roles){
            this.reorderRoleParents(roles,null,this.state.roles);
            this.setState({});
        }else {
            postJson("/role/getRoleList.x", null, (data) => {
                this.reorderRoleParents(data.data,null,this.state.roles);
            });
        }
    }

    componentDidUpdate(){
        /* 角色选择select的回调注册 */
        layui.form().on("select(roleSelect)",() =>{
            if(this.props.onChange)
                this.props.onChange();
        });
        layui.form().render();
    }

    /* 将无序的角色列表重构成按照父子关系排列的数组 */
    reorderRoleParents(roles,parent,ret){
        this.level += 1;
        for(let i=0; i<roles.length; i++){
            /* 假如是二级运营账号,则只允许创建物业类型角色账号 */
            if(this.props.isSeclevel && !this.userHasRole(roles[i].roleName,"property"))
                continue;

            if(roles[i].roleParent == "")
                roles[i].roleParent = null;

            if(roles[i].roleParent == parent){
                for(let j=1;j<this.level;j++) {
                    if(roles[i].gap)
                        roles[i].gap += "---";
                    else
                        roles[i].gap = "---";
                }

                ret.push(roles[i]);
                this.reorderRoleParents(roles,roles[i].roleName,ret);
            }
        }
        this.level -= 1;
    }

    /* 判断某个角色是否属于某个角色的子角色 */
    userHasRole(userRoleName, roleName) {
        if(this.state.roles[0] == '')
            return false;

        if (userRoleName == roleName)
            return true;

        for (let i = 0; i < this.state.roles.length; i++) {
            if (this.state.roles[i].roleName == userRoleName) {
                let parents = this.state.roles[i].roleParents?this.state.roles[i].roleParents.split(","):"";
                for (let j = 0; j < parents.length; j++) {
                    if (parents[j] == roleName)
                        return true;
                }
            }
        }
        return false;

    }

    render(){
        console.log(this.state);
        return(

            [<ButtonInput></ButtonInput>]
        )
    }
}